package transcation;

import message.TLender;
import org.apache.activemq.ActiveMQConnectionFactory;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import javax.ejb.ActivationConfigProperty;
import javax.ejb.MessageDriven;
import javax.jms.*;

/**
 * Created with Intel IDEA.
 *  将Lender客户端转换为消息驱动bean
 * @Auther: gjt
 * @Date: 2024/11/16 11:12
 */

@MessageDriven(
        activationConfig = {
                @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue"),
                @ActivationConfigProperty(propertyName = "destination", propertyValue = "jms/QLender")
        }
)
public class LenderMDB implements MessageListener {

    @Resource
    private ActiveMQConnectionFactory factory;
    private QueueConnection connection = null;
    private QueueSession session = null;

    // 初始化连接和会话
    @PostConstruct
    public void init(){
        try {
            connection = factory.createQueueConnection();
            session = connection.createQueueSession(true, Session.AUTO_ACKNOWLEDGE);
            connection.start();
        } catch (JMSException e) {
            throw new RuntimeException(e);
        }
    }

    // 销毁连接和会话
    @PreDestroy
    public void cleanUp(){
        try {
            connection.close();
        } catch (JMSException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void onMessage(Message message) {
        try {
            boolean accepted = false;

            // 从消息中获取数据
            MapMessage msg = (MapMessage) message;
            double salary = msg.getDouble("salary");
            double loanAmt = msg.getDouble("loanAmt");

            TLender tLender = new TLender(" ", "TQueue");
            // 将结果返回
            TextMessage textMessage = session.createTextMessage();
            textMessage.setText(accepted ? "Accepted!" : "Declined");
            textMessage.setJMSCorrelationID(message.getJMSMessageID());

            // 创建发送者并发送消息
            QueueSender sender = session.createSender((Queue) message.getJMSReplyTo());
            sender.send(textMessage);
            System.out.println("\n Waiting for loan requests ...");
        } catch (JMSException e) {
            throw new RuntimeException(e);
        }
    }

}
